package com.zyajac.springBootDemo.dao.Redis;


import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.ByteArrayOutputStream;

/**
  * Kryo 序列化工具
  * @author LZG
  * @date  2019/8/12
  **/
@Slf4j
public class KryoRedisSerializer<T> implements RedisSerializer<T> {

    // 空值 数组
    public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

    private static  final  ThreadLocal<Kryo> kryos =ThreadLocal.withInitial(Kryo::new);

    private Class<T> clazz;


    //构造方法
    public KryoRedisSerializer(Class<T> clazz){
        super();
        this.clazz = clazz;
    }

    //序列化
    @Override
    public byte[] serialize(T t) throws SerializationException {
        if(t== null) return EMPTY_BYTE_ARRAY;

        Kryo kryo = kryos.get();

        kryo.setReferences(false);
        kryo.register(clazz);

        try{
            ByteArrayOutputStream outputStream  = new ByteArrayOutputStream();
            Output output = new Output(outputStream);
            kryo.writeClassAndObject(output , t);
            output.flush();
            return outputStream.toByteArray();
        } catch (KryoException e) {
            e.printStackTrace();
        }

        return EMPTY_BYTE_ARRAY;
    }

    //反序列化
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {

        if(bytes == null || bytes.length <= 0 ) return null;

        Kryo kryo = kryos.get();
        kryo.setReferences(false);
        kryo.register(clazz);

        try{
            Input input = new Input(bytes);
            return (T) kryo.readClassAndObject(input);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
